import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List;


public class TankWar extends Frame {

	public static final int GAME_WIDTH = 500;
	public static final int GAME_HEIGHT = 400;
	
	Image offScreenImage = null;
	
	Tank tank = new Tank(50, 50, this);
	Tank enemyTank = new Tank(100, 100, false, this);
	
	List<Missile> missiles = new ArrayList<Missile>();

	public static void main(String[] args) {
		new TankWar().launchFrame();
	}
	
	

	@Override
	public void update(Graphics g) {
		if(offScreenImage == null){
			offScreenImage = this.createImage(500, 400);
		}
		
		Graphics gOffScreen = offScreenImage.getGraphics();
		Color c = gOffScreen.getColor();
		gOffScreen.setColor(Color.GREEN);
		gOffScreen.fillRect(0, 0, 500, 400);
		gOffScreen.setColor(c);
		paint(gOffScreen);
		g.drawImage(offScreenImage, 0, 0, null);
	}



	@Override
	public void paint(Graphics g) {
		tank.draw(g);
		for (int i = 0; i < missiles.size(); i++) {
			Missile missile = missiles.get(i);
			enemyTank.isHitByMissile(missile);
			missile.draw(g);
		}
		
		enemyTank.draw(g);
		
		g.drawString("Missile count: "+missiles.size(),	10, 40);
	}

	void launchFrame() {
		this.setBounds(400, 200, GAME_WIDTH, GAME_HEIGHT);
		this.setResizable(false);
		this.setBackground(Color.GREEN);
		this.setTitle("TankWar");
		this.addWindowListener(new WindowAdapter() {

			@Override
			public void windowClosing(WindowEvent arg0) {
				System.exit(0);
			}

		});
		this.addKeyListener(new KeyMonitor());
		this.setVisible(true);
		new Thread(new RepaintThread()).start();
	}
	
	class KeyMonitor extends KeyAdapter{

		@Override
		public void keyPressed(KeyEvent e) {
			tank.keyPressed(e);
		}

		@Override
		public void keyReleased(KeyEvent e) {
			tank.keyReleased(e);
		}
		
		
	}

	class RepaintThread implements Runnable {

		@Override
		public void run() {
			while (true) {
				try {
					Thread.sleep(50);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				repaint();
			}
		}

	}
}
